<template>
  <Drawer :visible="props.showModal" width="750" @close="modalCancelFn">
    <!--   【1】基础信息   -->
    <h2 class="title-sign">样本分装</h2>
    <Row class="base-info">
      <Col :span="8">
        样本名称: <Popover :content="props.data?.specimenName">{{ sliceStr(props.data?.specimenName, 9) }}</Popover>
      </Col>
      <Col :span="8"> 容量: {{ unitCheck(props.data?.capacity, props.data.unit) }} </Col>
      <Col :span="8">采样日期: {{ dayjs(props.data?.sampleTime).format('YYYY-MM-DD') }} </Col>
      <Col :span="8">
        样本编号: <Popover :content="props.data?.specimenSerial">{{ sliceStr(props.data?.specimenSerial, 9) }}</Popover>
      </Col>
      <Col :span="8" style="padding-right: 5px">
        样本类型：<Popover :content="props.data?.specimenType">{{ sliceStr(props.data?.specimenType, 9) }}</Popover>
      </Col>
      <Col :span="8">数字编号: {{ props.data?.serial }} </Col>
    </Row>
    <!--   【2】分装   -->
    <div class="base-info" style="margin-top: 10px">
      <Form layout="inline" :colon="false" labelAlign="left" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
        <FormItem label="分装数量" :rules="[{ required: true, message: '分装数量必填！' }]">
          <InputNumber style="width: 120px" v-model:value="state.dispensingData.splitCount" :min="0" />
        </FormItem>
        <FormItem label="分装容量" :rules="[{ required: true, message: '分装容量必填！' }]">
          <InputNumber style="width: 120px" v-model:value="state.dispensingData.splitCapacity" :min="0" :max="props.data?.capacity" />
        </FormItem>
        <FormItem>
          <div class="remainder">剩余：{{ unitCheck(props.data?.capacity - state.dispensingData.splitCapacity, props.data.unit) }}</div>
        </FormItem>
      </Form>
      <div style="margin-left: 223px; color: red">注意：分装容量不可大于现有容量！</div>
    </div>
    <!--   【3】表格   -->
    <div style="display: flex; justify-content: space-between">
      <span>分装情况：</span>
      <Button type="primary" class="scan">扫描二维码</Button>
    </div>
    <vxe-table :max-height="600" :show-overflow="false" ref="tableRef" style="margin-top: 15px" :data="state.dispensingList">
      <vxe-column field="capacity" title="容量">
        <template #default="{ row }">
          <InputNumber v-model:value="row.capacity" />
        </template>
      </vxe-column>
      <vxe-column field="unit" title="单位">
        <template #default="{ row }">
          <Select
            v-model:value="row.unit"
            :options="[
              { label: 'ml', value: 1 },
              { label: 'μl', value: 2 },
            ]"
            @change="unitChangeFn(row)"
          />
        </template>
      </vxe-column>
      <vxe-column field="serial" title="数字编号">
        <template #default="{ row }">
          <Input v-model:value="row.serial" />
        </template>
      </vxe-column>
    </vxe-table>
    <!--   【4】页脚   -->
    <template #footer>
      <div style="display: flex; justify-content: center">
        <Button type="white-blue" style="margin-right: 90px" @click="modalCancelFn">取消</Button>
        <Button type="blue-white" @click="modalOkFn">保存</Button>
      </div>
    </template>
  </Drawer>
</template>

<script setup lang="ts">
import { Drawer, Row, Col, Select, Input, Form, FormItem, InputNumber, Modal, message, Popover } from 'ant-design-vue';
import Button from '@/framework/components/basic/button/button.vue';
import { reactive, ref, watch } from 'vue';
import { sliceStr, unitCheck } from '@/libs/utils';
import { instance } from '@/modules/sample_manage/api';
import dayjs from 'dayjs';

type State = {
  dispensingList: any[];
  dispensingData: {
    splitCount: number;
    splitCapacity: number;
  };
};
/**
 * const
 */
const props = withDefaults(
  defineProps<{
    showModal: boolean;
    data: any;
  }>(),
  {
    showModal: false,
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'modalOk'): void;
}>();
const tableRef = ref();
const state: State = reactive({
  dispensingData: {
    splitCount: 0,
    splitCapacity: 0,
  },
  dispensingList: [],
});
watch([() => state.dispensingData.splitCount, () => state.dispensingData.splitCapacity], () => {
  let newArr;
  if (!state.dispensingData.splitCount) {
    state.dispensingData.splitCount = 1;
  }
  let itemCapacity = Math.floor((state.dispensingData.splitCapacity / state.dispensingData.splitCount) * 1000) / 1000;
  newArr = new Array(state.dispensingData.splitCount).fill(itemCapacity)?.map((item, index) => {
    let obj = {
      capacity: item,
      unit: props.data.unit === 1 ? 1 : 2,
      serial: '',
    };
    if (index > 0 && index === state.dispensingData.splitCount - 1) {
      obj.capacity = (state.dispensingData.splitCapacity * 1000 - item * 1000 * (state.dispensingData.splitCount - 1)) / 1000;
    }
    return obj;
  });
  state.dispensingList = newArr;
  tableRef.value?.reloadData(newArr);
});

/**
 * drawer
 */
const modalCancelFn = () => {
  state.dispensingList = [];
  state.dispensingData = { splitCount: 0, splitCapacity: 0 };
  emits('update:showModal', false);
};

const unitChangeFn = (row) => {
  row.capacity = row.unit === 1 ? (row.capacity / 1000).toFixed(3) : row.capacity * 1000;
};
// 判断数字编号是否重复
const containsDuplicate = (nums) => {
  return nums.length !== [...new Set(nums)].length;
};
const modalOkFn = () => {
  // 统一单位为ml
  // 样本分装总量
  let allCapacity = state.dispensingList.reduce((previousValue, currentValue) => {
    return (previousValue += currentValue.unit === 1 ? Number(currentValue.capacity) : currentValue.capacity / 1000);
  }, 0);
  if (allCapacity === 0 || state.dispensingList.some((item) => !item.capacity)) {
    message.warning('分装结果不能为空');
    return;
  }
  if (props.data.unit === 2) allCapacity = allCapacity * 1000;
  if ((allCapacity * 1000).toFixed(0) !== (state.dispensingData?.splitCapacity * 1000).toFixed(0)) {
    let a = '';
    if (allCapacity > state.dispensingData?.splitCapacity) a = '超出';
    if (allCapacity < state.dispensingData?.splitCapacity) a = '低于';
    message.warning(`分装结果的总容量${a}分装容量${unitCheck(Math.abs(Math.floor(allCapacity * 1000 - state.dispensingData?.splitCapacity * 1000) / 1000), props.data.unit)}`);
    return;
  }
  const modal = Modal.confirm({
    title: '确认保存吗?',
    onOk: async () => {
      if (state.dispensingList.some((item) => item.serial == '')) return message.warning('编码信息不能为空');
      if (containsDuplicate(state.dispensingList.map((item) => item.serial))) return message.warning('编码信息有重复');
      let capacity = Math.round(props.data?.capacity * 1000 - allCapacity * 1000) / 1000;
      let data = {
        id: props.data.id,
        childrenList: state.dispensingList,
        split_count: state.dispensingData?.splitCount,
        capacity,
      };
      await instance(data);
      message.success('操作成功！');
      modalCancelFn();
      emits('modalOk');
      modal.destroy();
    },
  });
};
</script>

<style scoped lang="less">
.title-sign {
  font-weight: 700;
}

.base-info {
  padding: 0 20px;
  line-height: 30px;
}

.remainder {
  width: 110px;
  height: 30px;
  padding: 0 10px;
  margin-left: 60px;
  line-height: 30px;
  border-radius: 5px;
  background-color: rgba(110, 199, 244, 19);
}

.scan {
  // width: 130px;
  // height: 30px;
  // line-height: 30px;
  // border-radius: 5px;
  // background-color: rgba(22, 119, 255, 100);
  // color: #fff;
  // font-size: 18px;
  // text-align: center;
}
</style>
